package com.fish.yssb.db;

import android.content.Context;
import android.util.Log;

import com.fish.yssb.db.bean.UserInfoTable;
import com.fish.yssb.ui.page.util.PrefeneceUtil;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmObject;
import io.realm.RealmResults;
import io.realm.Sort;

import static com.fish.yssb.app.UnCeHandler.TAG;


/**
 * Used 尺寸转换工具类（全）
 */
public class RealmDb {
    public static Realm realm;
    private static RealmConfiguration config;
    private static String key = "huangxiaoguo1234"; //可以需要16，循环4次，共64位key

    private static RealmDb realmDb;

    public static RealmDb getInstance () {
        if ( realmDb == null ) {
            realmDb = new RealmDb();
        }
        return realmDb;
    }


    /**
     * 获取Realm数据库64位秘钥
     *
     * @param key
     * @return
     */
    public static byte[] getRealmKey(String key) {
        String newKey = "";
        for (int i = 0; i < 4; i++) {
            newKey = newKey + key;
        }
        return newKey.getBytes();
    }

    //初始化
    public static void initRealm(Context context)
    {

        CustomMigration realmMigration = new CustomMigration();

        realm.init(context);

        RealmConfiguration config = new RealmConfiguration.Builder()
                //设置数据库名称
                .name( "test8.realm" )
                //设置数据库版本
                .schemaVersion( 3)
                //版本变化时（迁移操作），怎么处理。。。
                .migration( realmMigration )
                //版本冲突时自动删除原数据库
                .deleteRealmIfMigrationNeeded()
                .build();

        try {
            //手动调用Realm.migrateRealm()，不手动调起此方法，使用时才会调起RealmMigration
            Realm.migrateRealm( config, realmMigration );
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        realm = Realm.getInstance( config );


    }


    /**
     * 添加指定类到数据库
     * 新增和更新，需要有PrimaryKey，不然没法更新
     * @param info
     */
    public static void insertOrUpdataRealmObject(RealmObject info){
//        realm = Realm.getInstance(config);
        realm.beginTransaction();
        realm.copyToRealmOrUpdate(info);
        realm.commitTransaction();
        //realm.close();
    }

    /**
     * 添加json指定类到数据库
     * 新增和更新，需要有PrimaryKey，不然没法更新
     * @param info
     */
    public static void insertOrUpdataRealmJSON(RealmObject info, String json){
//        Realm realm = Realm.getInstance(config);
        realm.beginTransaction();
        realm.createObjectFromJson(info.getClass(),json);
        realm.commitTransaction();
        //realm.close();
    }


    /**
     * 添加指定类到数据库
     * 新增 不能有PrimaryKey，不然重复的key会报错
     * @param info
     */
    public static void insertRealmObject(final RealmObject info){


//        realm.beginTransaction();
//        realm.copyToRealm(info);
//        realm.commitTransaction();

        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealmOrUpdate(info);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                //操作成功
                Log.e(TAG, "onSuccess: insertRealmObject" );
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                //操作失败
                Log.e(TAG, "onError: "+error.getMessage());
            }
        });
    }

    /**
     * 批量插入数据
     * @param infos
     */
    public static void insertRealmObjects(final List<? extends RealmObject> infos)
    {
//        realm.beginTransaction();
//        //要使用update这种方法，那插入的对象必须是有主键的
//        realm.copyToRealmOrUpdate(infos);
//        realm.commitTransaction();

        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealmOrUpdate(infos);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                //操作成功
                Log.e(TAG, "insertRealmObjects onSuccess: " );
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                //操作失败
                Log.e(TAG, " insertRealmObjects onError: "+error.getMessage());
            }
        });
    }

    /**
     * 查询指定类的全部存储信息
     * @return
     * @param clazz
     */
    public static List<? extends RealmObject> queryRealmObjects(final Class<? extends RealmObject> clazz){
//        Realm realm = Realm.getInstance(config);
        RealmResults<? extends RealmObject> realmResults = realm.where(clazz).findAll();
        List<? extends RealmObject> arrayList = realm.copyFromRealm(realmResults);
        //realm.close();
        return arrayList;
    }


    /**
     * 查询指定类的全部存储信息
     * @return
     * @param clazz
     */
    public static List<? extends RealmObject> queryRealmObjectsByData(final Class<? extends RealmObject> clazz,
                                                                      String strkey,int strVal){
//        Realm realm = Realm.getInstance(config);
        RealmResults<? extends RealmObject> realmResults = realm.where(clazz).equalTo(strkey,strVal).findAll();
        realmResults.sort("idSort", Sort.DESCENDING) ; //排序
        List<? extends RealmObject> arrayList = realm.copyFromRealm(realmResults);
        //realm.close();
        return arrayList;
    }


    /**
     * 删除指定类的全部数据库信息
     */
    public static void deleteRealmObjects(final Class<? extends RealmObject> clazz){

//        realm.beginTransaction();
//        realm.delete(clazz);
//        realm.commitTransaction();

        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.delete(clazz);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                //操作成功
//                Log.e(TAG, "onSuccess: " );
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                //操作失败
//                Log.e(TAG, "onError: "+error.getMessage());
            }
        });

    }

    /**
     *
     * 删除此realm对应的全部数据库信息
     * 删除所有表数据
     */
    public static void deleteAllRealmObjects(){
//       Realm realm = Realm.getInstance(config);
        realm.beginTransaction();
        realm.deleteAll();
        realm.commitTransaction();
        //realm.close();
    }

    public static RealmResults<UserInfoTable> selUserInfo(String name){
//       Realm realm = Realm.getInstance(config);
        RealmResults<UserInfoTable> sel = realm.where(UserInfoTable.class).equalTo("name",name).findAll();;

       return sel;
        //realm.close();
    }


    public static void deleteAllRealmUserInfoTable(UserInfoTable info){
//       Realm realm = Realm.getInstance(config);
        RealmResults<UserInfoTable> sel = realm.where(UserInfoTable.class).equalTo("name",info.getName()).findAll();;

        realm.beginTransaction();
        sel.deleteAllFromRealm();
        realm.commitTransaction();
        //realm.close();
    }

    public static List<? extends RealmObject> queryRealmObjects_log(final Class<? extends RealmObject> clazz){
//        Realm realm = Realm.getInstance(config);

        RealmResults<? extends RealmObject> realmResults = realm.where(clazz).findAll();
        realmResults = realmResults.sort("l_time", Sort.ASCENDING) ; //排序
        List<? extends RealmObject> arrayList = realm.copyFromRealm(realmResults);

        //realm.close();
        return arrayList;
    }

    public static List<? extends RealmObject> queryRealmObjects_log_byName(final Class<? extends RealmObject> clazz,String name){
//        Realm realm = Realm.getInstance(config);
        RealmResults<? extends RealmObject> realmResults = realm.where(clazz).equalTo("opertioner",name).findAll();
        realmResults = realmResults.sort("l_time", Sort.ASCENDING) ; //排序
        List<? extends RealmObject> arrayList = realm.copyFromRealm(realmResults);

        //realm.close();
        return arrayList;
    }

    public static List<? extends RealmObject> queryRealmObjectsByDataBy_byName(final Class<? extends RealmObject> clazz,
                                                                        long stime,long etime,String name){
//        Realm realm = Realm.getInstance(config);
        RealmResults<? extends RealmObject> realmResults = realm.where(clazz).equalTo("opertioner",name).between("l_time",stime,etime).findAll();
        realmResults.sort("l_time", Sort.DESCENDING) ; //排序
        List<? extends RealmObject> arrayList = realm.copyFromRealm(realmResults);
        //realm.close();
        return arrayList;
    }


    public static List<? extends RealmObject> queryRealmObjectsByDataBy(final Class<? extends RealmObject> clazz,
                                                                      long stime,long etime){
//        Realm realm = Realm.getInstance(config);
        RealmResults<? extends RealmObject> realmResults = realm.where(clazz).between("l_time",stime,etime).findAll();
        realmResults.sort("l_time", Sort.DESCENDING) ; //排序
        List<? extends RealmObject> arrayList = realm.copyFromRealm(realmResults);
        //realm.close();
        return arrayList;
    }


}